# -*- coding: utf-8 -*-
from BeautifulSoup import BeautifulSoup
from django.db.models import Max, Min
from datetime import datetime, timedelta
from django import template
from django.db.models.query_utils import Q
from django.template.loader import render_to_string
from django.conf import settings
from core.models import Category
from ..models import Record

register = template.Library()

@register.simple_tag(takes_context=True)
def short_story(context, record):
    return render_to_string(
        "%s/news/short_story.html" % settings.LIVE_ENGINE_TEMPLATE, {
            'record': record
        },
        context_instance = context
    )


@register.simple_tag()
def top_news(interval):

    categories_id = Category.objects.all().values_list('pk', flat=True)

    records = Record.objects.filter(
        status = Record.STATUS_PUBLISHED,
        publish_date__gte = (datetime.now()-timedelta(days=interval)),
        publish_date__lte = datetime.now(),
        category__pk__in = categories_id
    ).order_by('-rating')[:5]

    return render_to_string(
        "%s/news/top_news.html" % settings.LIVE_ENGINE_TEMPLATE, {
            'records': records
        }
    )

@register.simple_tag(takes_context=True)
def archive_news(context):

    path = context.get('request').path
    # Это вообще тупой хардкод... нужно перенести на ОРМ
    if path == '/':
        items = Record.objects.raw("select id, publish_date, count(*) as count from news_record where publish_date <= now() and not publish_date is null group by year(publish_date), month(publish_date) order by publish_date desc")
    else:
        items = None

    return render_to_string(
        "%s/news/archive_news.html" % settings.LIVE_ENGINE_TEMPLATE, {
            'items': items
        }
    )

@register.simple_tag()
def related_news(record):
    categories_id = Category.objects.all().values_list('pk', flat=True)

    ids = Record.objects.raw("select id, title from news_record where match(title) against(\"%s\") and not id=%s limit 5" % (record.title, record.id))
    ids_list = []
    for id in ids:
        ids_list.append(id.id)

    records = Record.objects.filter(
        Q(status = Record.STATUS_PUBLISHED) &
        Q(publish_date__lte = datetime.now()) &
        Q(pk__in = ids_list)
    )

    if records.count() < 2:
        records = Record.objects.filter(
            Q(status = Record.STATUS_PUBLISHED) &
            Q(publish_date__lte = datetime.now()) &
            Q(category = record.category) &
            ~Q(pk = record.pk)
        ).order_by("-views")[0:5]

    return render_to_string(
        "%s/news/related_news.html" % settings.LIVE_ENGINE_TEMPLATE, {
            'records': records
        }
    )

@register.filter()
def schema(story):
    try:
        soup = BeautifulSoup(story)
        img = soup.find('img')
        img['itemprop'] = "contentURL"
        return soup.prettify()

    except Exception, e:
        return story

    #itemprop="name"


@register.filter()
def schema_name(title):
    try:
        if ("(" in title) and (")" in title):
            parts = title.split("(")
            return """
                <span itemprop="name">%s</span> (%s
            """ % (parts[0], parts[1])
        else:
            return title	
    except Exception, e:
        return title
